package cn.wolfcode.wolf2w.resolver;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.interceptor.UserParam;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/*
* 用于解析请求映射方法中声明当前登录用户信息
* */
public class UserInfoArgumentResolver implements HandlerMethodArgumentResolver{
    @Autowired
    private IUserInfoRedisService userInfoRedisService;
    //表示当前解析器能解析哪种类型参数
    //返回值boolean，true表示支持指定类型，false不支持
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //表示当前解析那种类型参数
      return   parameter.getParameterType()== UserInfo.class
              && parameter.hasParameterAnnotation(UserParam.class);

    }

    //执行参数解析逻辑，并注入到参数中
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        //获取当前用户对象
        HttpServletRequest req = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = req.getHeader("token");
        return userInfoRedisService.getUserInfo(token);
    }
}
